package com.hunantv.mglive.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by qiudaaini@163.com on 15/12/23.
 */
public class Toast {
    public static final int LENGTH_SHORT = 0;
    public static final int LENGTH_LONG = 1;
    private static final List<CharSequence> mToastStrList = new ArrayList<>();
    private Context mContext;
    private CharSequence mText;
    private int mDuration;
    private int mGravity = -999;
    private int mX;
    private int mY;
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            synchronized (mToastStrList) {
                if (msg.obj != null) {
                    mToastStrList.remove(msg.obj);
                }
            }
        }
    };

    private Toast() {

    }

    public static Toast makeText(Context context,int resid, int duration) {
        Toast toast = new Toast();
        toast.mContext = context;
        toast.mText = context.getString(resid);
        toast.mDuration = duration;
        return toast;
    }

    public static Toast makeText(Context context, CharSequence text, int duration) {
        Toast toast = new Toast();
        toast.mContext = context;
        toast.mText = text;
        toast.mDuration = duration;
        return toast;
    }

    public void show() {
        if (mContext != null && mText != null && !mText.equals("") && !"null".equals(mText)) {
            synchronized (mToastStrList) {
                if (mToastStrList.contains(mText)) {
                    return;
                }
                mToastStrList.add(mText);
            }
            try {
                android.widget.Toast toast = android.widget.Toast.makeText(mContext, mText, mDuration);
                TextView tv = (TextView) toast.getView().findViewById(android.R.id.message);
                tv.setGravity(Gravity.CENTER);
                if (mGravity != -999) {
                    toast.setGravity(mGravity, mX, mY);
                }
                toast.show();
                Message msg = mHandler.obtainMessage(0, mText);
                mHandler.sendMessageDelayed(msg, 3000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

//    public void setGravity(int gravity, int x, int y) {
//        this.mGravity = gravity;
//        this.mX = x;
//        this.mY = y;
//    }

}
